﻿using System;
using TimerTask.Common.Utils;
using TimerTask.Model.Entity;

namespace TimerTask.Service.NotifyTools
{
    public class EmailNotify : INotify
    {
        private EmailNotify()
        {
        }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string Smtp { get; set; }

        public const int NotifyCode = 1;
        private static EmailNotify _instance;
        public static EmailNotify Instance()
        {
            if (_instance == null)
            {
                _instance = new EmailNotify
                {
                    UserName = AppConfig.Instance.EmailNotify.UserName,
                    Password = AppConfig.Instance.EmailNotify.Password,
                    Smtp = AppConfig.Instance.EmailNotify.Smtp
                };
            }
            return _instance;
        }
        public void Notify(JobInfo job, bool isSuccessed, string res)
        {
            string status = "调用失败";

            if (isSuccessed)
            {
                status = "恢复正常";
            }
            string subject = string.Format("[定时任务] {0} {1} - {2}", job.JobName, status, DateTime.Now.ToString("yyyy MM dd HH:mm:ss"));

            LogUtil.Error(subject + "\n返回内容:\n" + res, job.JobName);

            if (string.IsNullOrEmpty(res))
            {
                res = "null";
            }

            if (res.Length > 255)
            {
                res = res.Substring(0, 255) + "...";
            }
            res = "返回内容:\n" + res;
            EmailUtil.SendEmailAsync(job.ContactEmail, subject, res).GetAwaiter().GetResult();
        }
    }
}
